package com.zy.smartdb.service;

import com.zy.smartdb.pojo.FieldInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description:
 * @Author: zara
 * @Version V3.0
 * @Date: 2022/11/21 3:34 下午
 */

@Service
public class DbService {


    @Autowired
    JdbcTemplate jdbcTemplate;

    public Map<String, FieldInfo> getTableInfo(String tableName) {
        String sql = "select * from " + tableName + "  limit 0";
        ResultSet tabs;

        Map<String, FieldInfo> fieldInfos = new HashMap<>();
        try {
            Connection connection = this.jdbcTemplate.getDataSource().getConnection();
            DatabaseMetaData dbMetaData = connection.getMetaData();
//            String[] types = {"TABLE"};
//            tabs = dbMetaData.getTables(connection.getCatalog(), "root", tableName, types);
//            tabs = dbMetaData.getTables(connection.getCatalog(), connection.getCatalog(), tableName, types);
//            while (tabs.next()) {
//                String tableName1 = tabs.getString("TABLE_NAME");
//                String tableSchema = tabs.getString("TABLE_SCHEM");
            ResultSet resultSet = dbMetaData.getColumns(connection.getCatalog(), connection.getCatalog(), tableName, null);
            while (resultSet.next()) {
                String name = resultSet.getString("COLUMN_NAME");
                String type = resultSet.getString("TYPE_NAME");
                String colRemarks = resultSet.getString("REMARKS");
                int size = resultSet.getInt("COLUMN_SIZE");
                fieldInfos.put(name, new FieldInfo(name, type, colRemarks, size));
            }
//            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fieldInfos;
    }
}
